package com.lyswkjxgs.report.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lyswkjxgs.report.domain.ConfigDTO;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 配置服务类
 */
@Service
public class ConfigService {

    @Value("${config.dir.name}")
    private String configDirName;

    @Value("${config.name}")
    private String configName;

    public ConfigDTO getConfig(){
        ObjectMapper objectMapper = new ObjectMapper();
        File targetFile = getTargetFile();
        if (!targetFile.exists()){
            return new ConfigDTO();
        }
        try {
            return objectMapper.readValue(targetFile, ConfigDTO.class);
        }catch (IOException exception){
            throw new RuntimeException(exception);
        }
    }

    public void saveConfig(ConfigDTO configDTO){
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] content = null;
        try {
            content = objectMapper.writeValueAsBytes(configDTO);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        File file = getTargetFile();
        try (FileOutputStream fileOutputStream = FileUtils.openOutputStream(file);){
            fileOutputStream.write(content);
        }catch (IOException exception){
            throw new RuntimeException(exception);
        }
    }

    private File getTargetFile(){
        File userHome = SystemUtils.getUserHome();
        File dirFile = new File(userHome, configDirName);
        File file = new File(dirFile, configName);
        return file;
    }
}
